package com.quick.develop.flowable.framework.cmd.admin;

import org.flowable.common.engine.impl.interceptor.Command;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.engine.runtime.ActivityInstance;

import java.io.Serializable;
import java.util.List;

import static com.quick.develop.framework.utils.collection.CollectionUtils.convertList;

/**
 * @author junyuan.liu
 * @description: 流程跳转 无限制
 * @date 2022/9/18 9:57
 */
public class ProcessChangeStateCmd implements Command<Void>, Serializable {
    private static final long serialVersionUID = -7530576538928461063L;
    
    protected String processInstanceId;
    protected String targetActId;
    
    public ProcessChangeStateCmd(String processInstanceId, String targetActId) {
        this.processInstanceId = processInstanceId;
        this.targetActId = targetActId;
    }

    @Override
    public Void execute(CommandContext commandContext) {
        ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
        RuntimeService runtimeService = processEngineConfiguration.getRuntimeService();
        List<ActivityInstance> list = getRunActInstances(runtimeService);
        List<String> ids = convertList(list, ActivityInstance::getActivityId);

        runtimeService.createChangeActivityStateBuilder()
                .processInstanceId(processInstanceId)
                .moveActivityIdsToSingleActivityId(ids, targetActId)
                .changeState();

        return null;
    }
    
    private List<ActivityInstance> getRunActInstances(RuntimeService runtimeService) {
        
        return runtimeService.createActivityInstanceQuery()
                .processInstanceId(processInstanceId).unfinished()
                .list();
    }
}
